package com.topofstack.flp.ui;

import java.io.File;

import com.bappi.custom.activities.CustomActivity;
import com.topofstack.flp.FLPApplication;
import com.topofstack.flp.R;
import com.topofstack.flp.utils.Utils;
import com.topofstack.flp.utils.VideoThumbnailAdapter;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;


public class VideoGalleryActivity extends CustomActivity implements OnClickListener {
	
	
	Gallery gallery;
	FLPApplication application;
	File[] videoFiles;
	
	boolean is_delete;
	
	Button btnDelete;
	Button btnPlay;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_video_gallery);
		
		if(getIntent().getExtras() != null){
			is_delete = getIntent().getExtras().getBoolean("is_delete", false);
		}
		else{
			is_delete = false;
		}
		
		btnDelete = (Button)findViewById(R.id.btnDelete);
		btnDelete.setOnClickListener(this);
		
		btnPlay = (Button)findViewById(R.id.btnPlay);
		btnPlay.setOnClickListener(this);
		
		
		btnDelete.setVisibility(View.INVISIBLE);
		btnPlay.setVisibility(View.INVISIBLE);
		
		application = (FLPApplication)getApplication();
		gallery = (Gallery)findViewById(R.id.gallery);
		
		gallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if(is_delete){
					btnDelete.setVisibility(View.VISIBLE);
				}
				else{
					btnPlay.setVisibility(View.VISIBLE);	
				}
			}
		});
		
		refreshGallery();
	}
	
	
	private void refreshGallery(){
		try {
			videoFiles = application.getAssetManager().getAllVideoFiles();
			Log.i("DREG", "SIZE="+videoFiles.length);
			VideoThumbnailAdapter vta = new VideoThumbnailAdapter(this, videoFiles);
			gallery.setAdapter(vta);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void onClick(View sender) {
		
		if(sender == btnDelete){
			int position = gallery.getSelectedItemPosition();
			if(position != -1){
				videoFiles[position].delete();
				Utils.showAlertMessage(getParent(), "", "Video deleted successfully");
				finish();
			}
		}
		else if(sender == btnPlay){
			int position = gallery.getSelectedItemPosition();
			if(position != -1){
				Intent intent = new Intent();
			    intent.setAction(Intent.ACTION_VIEW);
			    intent.setDataAndType(Uri.fromFile(videoFiles[position]), "video/*");
			    startActivity(intent);
				finish();
			}			
		}
	}

}
